<?php

namespace App\Admin\Controllers;

use App\Models\Estate;
use Encore\Admin\Form;
use App\Models\Product;
use App\Models\ProductSku;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\AdminController;
use App\Admin\Tools\SkuGridReturnProductButton;
use App\Supports\Product\ProductPosterCleaner;

class ProductSkusController extends AdminController
{
    protected $title = '商品 SKU 管理';
	
	protected function product($id = null)
	{
		$productId = $id ?? request('product_id');
		if (!$product = Product::find($productId)) {
			return back()->with(admin_error('必须依附于商品主体'));
		}
		return $product;
	}
 
	public function edit($id, Content $content)
	{
		return $content
			->title($this->title())
			->description($this->description['edit'] ?? trans('admin.edit'))
			->body($this->form($id)->edit($id));
	}
	
	protected function form($id = null)
    {
        $form = new Form(new Product());
	
        $product = $this->product($id);
	    
	    $form->hasMany('skus', "商品：{$product->title}", function ($form) use ($product) {
		    
	    	$form->text('name', 'SKU 名称')
			    ->rules('required');
	    	
	    	$form->text('code', 'SKU 货号');
		    
		    $form->text('brief', 'SKU 简述');
		    
		    $form->image('pic', 'SKU 封面')
			    ->creationRules('required|unique:product_skus')
			    ->uniqueName()
			    ->help('NOTE：保证清晰的前提下尽可能压缩体积');
		
		    $form->divider();
		
		    $form->currency('price_cost', '成本价')
			    ->symbol('￥')
			    ->rules('required|numeric');
		    
		    $form->currency('price', '零售价')
			    ->symbol('￥')
			    ->rules('required|numeric');
		    
		    $form->currency('price_vip', '会员价')
			    ->symbol('￥')
			    ->rules('nullable|numeric');

			$form->currency('rewards', '佣金')
			    ->symbol('￥')
			    ->rules('nullable|numeric');
			$form->display('own_rewards', '自购返还佣金');
			$form->display('parent_rewards', '上级返还佣金');
		    
		    $form->number('stock', '剩余库存')
			    ->rules('required')
			    ->min(0)->default(1);
		    
		    $this->formAttribute($form, $product);
	    });
	    
	    $this->formTools($form);
	    $this->formFooter($form);
	    $this->formSaving($form);
	    $this->formSaved($form);
	
	    $form->setAction("/admin/product-skus/{$id}?product_id={$id}");

        return $form;
    }
    
    protected function formAttribute($form, Product $product)
    {
	    $attrGroup = $product->attributeGroup;
	    $attrKeys = $attrGroup ? $attrGroup->attributeKeys : collect();
	    if ($attrKeys->isNotEmpty()) {
		    $form->embeds('attr_value', '属性值', function ($form) use ($attrKeys) {
			    foreach ($attrKeys as $key) {
				    $form->text($key->id, $key->key)->required();
			    }
		    });
	    }
    }
    
    protected function formTools(Form $form)
    {
	    $form->tools(function (Form\Tools $tools) {
	    	$tools->disableList();
	    	$tools->disableView();
	    	$tools->disableDelete();
		    $tools->prepend('
		        <a
                    href="'.route('admin.products.index').'"
                    class="btn btn-sm btn-default" style="margin-right: 5px">
                    <i class="fa fa-list"></i> 列表
                </a>
	        ');
	    });
    }
    
    protected function formFooter(Form $form)
    {
	    $form->footer(function (Form\Footer $footer) {
	    	$footer->disableViewCheck();
	    	$footer->disableCreatingCheck();
	    	$footer->disableEditingCheck();
	    });
    }

    protected function formSaving(Form $form)
    {
        $form->saving(function (Form $form) {
          	app(ProductPosterCleaner::class)->clear($form->model(), \request('skus'));
        });
    }
	
	protected function formSaved(Form $form)
	{
		$form->saved(function (Form $form) {
			$skus = ProductSku::where('product_id',$form->model()->id)->get();
			
			foreach($skus as $sku){
				$sku->updateRewardsToSkus();
			}
			return redirect(route('admin.products.index'));
		});
	}
}
